/**
 * rtmp 播放器
 * 需引入 video.js 也可npm安装
 * 基本参数如下
 *   width: 650,
 *   height: 500,
 *   autoplay: true,
 *   controls: false,
 *   notSupportedMessage: '您的浏览器没有安装或开启Flash,戳我开启！',
 *   techOrder: ["html5", "flash"],
 *   sources: [{src: 'rtmp://live.hkstv.hk.lxdns.com/live/hks', type: 'rtmp/mp4'}],
 *   poster:picUrl || pathUrl('images/map/nopic.jpg'),
 */
/* eslint-disable */
import {Component} from 'react';
import _ from 'lodash';
import {videojs} from 'video';
class VideoPlayer extends Component {

  componentDidMount () {
    this.init();
  }

  componentWillReceiveProps(nProps) {
    if(!_.isEqual(nProps, this.props)) {
      if (this.player) {
        this.player.src(nProps.sources || []);
        this.player.load();
        this.player.play();
      }
    }
  }

  componentWillUnmount () {
    if (this.player) {
      this.player.dispose();
    }
  }

  init = (props = this.props) => {
    videojs.options.flash.swf = require('../../../../public/video-js.swf');
    this.player = videojs(this.videoNode, props, function onPlayerReady () {
      this.on('mouseup', (e)=>{//双击全屏
        if(this.clickTime){
          const dtime = new Date() - this.clickTime;
          if(dtime < 500){
            if(!this.isFullscreen()){
              this.requestFullscreen();
            }else{
              this.exitFullscreen();
            }
            this.clickTime = null;
          }else{
            this.clickTime = new Date();
          }

        }else{
          this.clickTime = new Date();
        }
      });
    });
  }

  // 自动点击播放按钮  在暂停状态下
  clickPlayButton = () => {
    let playBtn = document.getElementsByClassName("vjs-big-play-button")[0];
    let pausedBtn = document.getElementsByClassName("vjs-play-control vjs-control vjs-button vjs-paused")[0];
    
    if(playBtn) {
      playBtn.click()
    }else {
      pausedBtn && pausedBtn.click()
    }
  }

  render () {
    const id = parseInt(Math.random() * 10000);
    return (
      <div style={{width: this.props.width, height: this.props.height}}>
        <video
          ref={node => this.videoNode = node}
          className="video-js vjs-default-skin vjs-big-play-centered"
          controls={true}
          preload="none"
          style={{width: "100%", height: "100%", pointerEvents: 'auto'}}
        >
          <p className="vjs-no-js">
            要查看此视频，请启用JavaScript，并考虑升级浏览器。
            <a href="http://videojs.com/html5-video-support/" target="_blank">
              支持 HTML5 视频
            </a>
          </p>
        </video>
        <div style={{display: "none"}}>
          <a id={"fullscreen" + id} onClick={this.requestFullscreen}></a>
        </div>
      </div>
    );
  }

  play = () => {
    // if (this.player) {
    //     this.player.play()
    // }
  }
  requestFullscreen = ()=>{
    if (this.player) {
      this.player.requestFullscreen()
    }
  }
  exitFullscreen = ()=>{
    if (this.player) {
      this.player.exitFullscreen()
    }
  }
}
export default VideoPlayer;
